package xin.nick.cloud.code.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xin.nick.cloud.code.dao.AuthCodeDao;
import xin.nick.cloud.pojo.AuthCode;
import xin.nick.cloud.service.EmailService;

import java.util.Objects;
import java.util.Optional;

/**
 * @author Nick
 * @date 2021/8/1
 * @description
 */
@RestController
@Slf4j
public class CodeController {

    @Autowired
    private AuthCodeDao authCodeDao;

    @Reference
    private EmailService emailService;

    /**
     * 创建验证码,并发送邮件到邮箱
     * @return
     */
    @RequestMapping("/code/create/{email}")
    public boolean create(@PathVariable("email") String email) {
        log.info("准备创建验证码发送到邮箱啦~ {}",email);

        // 随机码
        int codeInt = (int)((Math.random()*9+1)*100000);
        String codeString = String.valueOf(codeInt);
        AuthCode authCode = new AuthCode();
        authCode.setCode(codeString);
        authCode.setEmail(email);
        authCodeDao.save(authCode);

        return emailService.sendEmail(email, codeString);

    }

    /**
     * 校验验证码是否正确，0正确1错误2超时
     * @param email
     * @param code
     * @return
     */
    @RequestMapping("/code/validate/{email}/{code}")
    public int validate(@PathVariable("email") String email,
                            @PathVariable("code") String code) {
        log.info("让我看看验证码对不对~ {}:{}", email, code);
        AuthCode queryAuthCode = new AuthCode();
        queryAuthCode.setEmail(email);
        queryAuthCode.setCode(code);
        Example example = Example.of(queryAuthCode);
        Optional one = authCodeDao.findOne(example);
        if (one.isEmpty() || Objects.isNull(one.get())) {
            return 0;
        }
        return 1;
    }

}
